var canvases = [];
canvases.push(new fabric.Canvas('canvas'));
var canvas = canvases[0];
canvas.backgroundColor = '#fff';
var number = 0;
var countCanvas = 1;
var link = '';
var copiedObject;
var copiedObjects = new Array();
var current;
var list = [];
var state = [];
var index = 0;
var index2 = 0;
var action = false;
var refresh = true;
canvas.on("object:added", function (e) {
    var object = e.target;
    console.log('object:modified');
    if (action === true) {
        state = [state[index2]];
        list = [list[index2]];
        action = false;
        console.log(state);
        index = 1;
    }
    object.saveState();
    console.log(object.originalState);
    state[index] = JSON.stringify(object.originalState);
    list[index] = object;
    index++;
    index2 = index - 1;
    refresh = true;
});
canvas.on("object:modified", function (e) {
    var object = e.target;
    console.log('object:modified');
    if (action === true) {
        state = [state[index2]];
        list = [list[index2]];
        action = false;
        console.log(state);
        index = 1;
    }

    object.saveState();
    state[index] = JSON.stringify(object.originalState);
    list[index] = object;
    index++;
    index2 = index - 1;
    console.log(state);
    refresh = true;
});
CanvasControls = function ($scope) {

    $scope.rasterize = function () {
        if (!fabric.Canvas.supports('toDataURL')) {
            alert('This browser doesn\'t provide means to serialize canvas to an image');
        }
        else {
            window.open(canvas.toDataURL('png'));
        }
    };
    $scope.addBackground = function (value) {
        console.log(1);
        addBg(value);
    }

    $scope.addTitle = function () {

        addTexts("Title: Double click to edit", 'Comic Sans', 40);
    };
    $scope.addSubtitle = function () {
        addTexts("Subtitle: Double click to edit", 'Arial', 30);
    };
    $scope.addSubtitle2 = function () {
        addTexts("Subtitle 2: Double click to edit", 'Time New Roman', 20);
    };
    $scope.addBody = function () {
        addTexts("Body Text: Double click to edit", 'Time New Roman', 14);
    };
    $scope.toggleBold = function () {
        setActiveStyle('fontWeight',
                getActiveStyle('fontWeight') === 'bold' ? '' : 'bold');
    };
    $scope.toggleItalic = function () {
        setActiveStyle('fontStyle',
                getActiveStyle('fontStyle') === 'italic' ? '' : 'italic');
    };
    $scope.addPhoto = function (value) {
        var iconUrl = 'photos/' + value;
        addImage(iconUrl, 1);
    };
    $scope.addSocial = function (value) {
        var iconUrl = 'socials/' + value;
        addImage(iconUrl, 1);
    }

    $scope.removeSelected = function () {
        var activeObject = canvas.getActiveObject(),
                activeGroup = canvas.getActiveGroup();
        if (activeGroup) {
            var objectsInGroup = activeGroup.getObjects();
            canvas.discardActiveGroup();
            objectsInGroup.forEach(function (object) {
                canvas.remove(object);
            });
        }
        else if (activeObject) {
            canvas.remove(activeObject);
        }
    };
    $scope.sendBackwards = function () {
        var activeObject = canvas.getActiveObject();
        if (activeObject) {
            canvas.sendBackwards(activeObject);
        }
    };
    $scope.bringForward = function () {
        var activeObject = canvas.getActiveObject();
        if (activeObject) {
            canvas.bringForward(activeObject);
        }
    };
    $scope.bringToFront = function () {
        var activeObject = canvas.getActiveObject();
        if (activeObject) {
            canvas.bringToFront(activeObject);
        }
    };
    $scope.sendToBack = function () {
        var activeObject = canvas.getActiveObject();
        if (activeObject) {
            canvas.sendToBack(activeObject);
        }
    };
    $scope.alignText = function (value) {
        setActiveProp('textAlign', value.toLowerCase());
    }

    $scope.addBackgroundColor = function (value) {
        addBgColors(values);
    }

    $('#font-family').change(function () {
        var value = $(this).val();
        setActiveProp('fontFamily', value.toLowerCase());
    });
    $('#font-size').change(function () {
        var value = $(this).val();
        setActiveProp('fontSize', value.toLowerCase());
    });
    $('#colorSelector').ColorPicker({
        color: '#0000ff',
        onShow: function (colpkr) {
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            setActiveStyle('fill', '#' + hex);
        }
    });
    $("#slider").slider({
        range: "min",
        min: 1,
        max: 100,
        value: 100,
        slide: function (event, ui) {
            var value = ui.value;
            setActiveStyle('opacity', parseInt(value, 10) / 100);
        }
    });
    $('#sliderbackground').slider({
        range: "min",
        min: 1,
        max: 100,
        value: 100,
        slide: function (event, ui) {
            var value = ui.value;
            var _this;
            if (number === 0) {
                _this = $('#canvas').parent().find('canvas');
            } else {
                _this = $('#canvas-' + number).parent().find('canvas');
            }
            _this.css({'opacity': parseInt(value, 10) / 100});
        }
    });
}

function getRandomLeftTop() {
    var offset = 50;
    return {
        left: fabric.util.getRandomInt(0 + offset, 200 - offset),
        top: fabric.util.getRandomInt(0 + offset, 200 - offset)
    };
}

function getActiveProp(name) {
    var object = canvas.getActiveObject();
    if (!object)
        return '';
    return object[name] || '';
}

function setActiveProp(name, value) {
    var object = canvas.getActiveObject();
    if (!object)
        return;
    object.set(name, value).setCoords();
    canvas.renderAll();
}

function addBg(imageName) {
    var imageUrl = 'theme/FrontEnd/img/images/assets/background/' + imageName;
    canvas.setBackgroundColor({
        source: imageUrl,
        repeat: 'repeat',
    }, canvas.renderAll.bind(canvas));
}

function addBgColors(color) {
    canvas.setBackgroundColor(color, canvas.renderAll.bind(canvas));
}

function addImage(imageName, scale) {
    var random = getRandomLeftTop();
    var src = 'theme/FrontEnd/img/images/assets/' + imageName;
    fabric.util.loadImage(src, function (img) {
        var object = new fabric.Image(img);
        object.set({
            left: random['left'],
            top: random['top']
        });
        canvas.add(object);
        canvas.renderAll();
    }, null, {crossOrigin: 'Anonymous'});
    canvas.renderAll();
}
;
function addTexts(text, font, size) {
    var random = getRandomLeftTop();
    var iText = new fabric.IText(text, {
        left: random['left'],
        top: random['top'],
        fontFamily: font,
        fontSize: size,
        fill: '#333',
        padding: 20,
        lockScalingX: true,
        lockScalingY: true
    });
    canvas.add(iText);
}



function setActiveStyle(styleName, value, object) {
    object = object || canvas.getActiveObject();
    if (!object)
        return;
    if (object.setSelectionStyles && object.isEditing) {
        var style = {};
        style[styleName] = value;
        object.setSelectionStyles(style);
        object.setCoords();
    }
    else {
        object[styleName] = value;
    }

    object.setCoords();
    canvas.renderAll();
}
;
function removeSelected() {
    var activeObject = canvas.getActiveObject(),
            activeGroup = canvas.getActiveGroup();
    if (activeGroup) {
        var objectsInGroup = activeGroup.getObjects();
        canvas.discardActiveGroup();
        objectsInGroup.forEach(function (object) {
            canvas.remove(object);
        });
    }
    else if (activeObject) {
        canvas.remove(activeObject);
    }
}
;
function _getActiveStyle(styleName, object) {
    object = object || canvas.getActiveObject();
    if (!object)
        return '';
    return (object.getSelectionStyles && object.isEditing)
            ? (object.getSelectionStyles()[styleName] || '')
            : (object[styleName] || '');
}
;
function _preview_canvas() {
    window.open(
            'data:image/svg+xml;utf8,' +
            encodeURIComponent(canvas.toSVG()));
}

function _download_canvas() {
    if (!fabric.Canvas.supports('toDataURL')) {
        alert('This browser doesn\'t provide means to serialize canvas to an image');
    }
    else {
        window.open(canvas.toDataURL('png'));
    }
}
canvas.on('mouse:move', function (e) {
    canvas.calcOffset();
});
function saveTemplate(id) {

    var data = JSON.stringify(canvas);
    $.ajax({
        url: hostname + '/admin/templates/edit/' + id,
        data: {
            action: 'saved',
            data: data,
            base64data: canvas.toDataURL('png')
        },
        type: 'post',
        success: function (response) {
            if (response == 'saved') {
                alert('Saved');
            } else {
                alert(response);
            }
        }
    });
}

function undo() {

    if (index <= 0) {
        index = 0;
        return;
    }

    if (refresh === true) {
        index--;
        refresh = false;
    }

    console.log('undo');
    index2 = index - 1;
    current = list[index2];
    current.setOptions(JSON.parse(state[index2]));
    index--;
    current.setCoords();
    canvas.renderAll();
    action = true;
}

function redo() {

    action = true;
    if (index >= state.length - 1) {
        return;
    }

    console.log('redo');
    index2 = index + 1;
    current = list[index2];
    current.setOptions(JSON.parse(state[index2]));
    index++;
    current.setCoords();
    canvas.renderAll();
}

function selectAll() {
    var objs = canvas.getObjects().map(function (o) {
        return o.set('active', true);
    });
    var group = new fabric.Group(objs, {
        originX: 'center',
        originY: 'center'
    });
    canvas._activeObject = null;
    groupobjs = canvas.setActiveGroup(group.setCoords()).renderAll();
}

function copy() {
    var objectActive = canvas.getActiveObject();
    var objectAciveGroup = canvas.getActiveGroup();
    if (objectAciveGroup) {
        canvas.discardActiveGroup();
        for (var i in objectAciveGroup.objects) {
            var object = fabric.util.object.clone(objectAciveGroup.objects[i]);
            object.set("top", objectAciveGroup.objects[i].top + 15);
            object.set("left", objectAciveGroup.objects[i].left + 15);
            copiedObjects[i] = object;
        }
    }
    else if (objectActive) {
        var object = fabric.util.object.clone(objectActive);
        object.set("top", objectActive.top + 15);
        object.set("left", objectActive.left + 15);
        copiedObject = object;
        copiedObjects = new Array();
    }
}
function cut() {
    var objectActive = canvas.getActiveObject();
    var objectAciveGroup = canvas.getActiveGroup();
    if (objectAciveGroup) {
        canvas.discardActiveGroup();
        for (var i in objectAciveGroup.objects) {
            var object = fabric.util.object.clone(objectAciveGroup.objects[i]);
            object.set("top", objectAciveGroup.objects[i].top + 15);
            object.set("left", objectAciveGroup.objects[i].left + 15);
            copiedObjects[i] = object;
            canvas.remove(objectAciveGroup.objects[i]);
        }

    }
    else if (objectActive) {
        var object = fabric.util.object.clone(objectActive);
        object.set("top", objectActive.top + 15);
        object.set("left", objectActive.left + 15);
        copiedObject = object;
        copiedObjects = new Array();
        canvas.remove(objectActive);
    }
    canvas.renderAll();
}

function paste() {
    if (copiedObjects.length > 0) {
        for (var i in copiedObjects) {
            canvas.add(copiedObjects[i]);
        }
    }
    else if (copiedObject) {
        canvas.add(copiedObject);
    }
    canvas.renderAll();
}

function changeWidthCanvas() {
    var w = $('#canwidth').val();
    if (isNaN(w) || w > 5000) {
        alert("Size is wrong");
        return;
    }
    else {
        var newWidth = $('#canwidth').val() / $('canvas').width();
        if ($("#checkResize").prop('checked', true)) {
            for (var i = 0; i < canvases.length; i++) {
                if (canvases[i] != null) {
                    canvas = canvases[i];
                    selectAll(); //select all object

                    var objectActive = canvas.getActiveObject(); //object
                    var objectAciveGroup = canvas.getActiveGroup(); //objects
                    if (objectAciveGroup) {
                        var objectsInGroup = objectAciveGroup.getObjects();
                        canvas.discardActiveGroup();
                        objectsInGroup.forEach(function (object) {
                            if ((object.get('type') == 'i-text')) {
                                fonsize = object.get('fontSize') * newWidth;
                                setActiveStyle('fontSize', fonsize, object);
                                object.set({top: objTop,
                                    left: objLeft * newWidth});
                            }
                            else {
                                objTop = object.getTop();
                                objLeft = object.getLeft();
                                objWidth = object.getWidth();
                                objHeight = object.getHeight();
                                object.setWidth(objWidth * newWidth);
                                object.setHeight(objHeight * newWidth);
                                object.set({top: objTop,
                                    left: objLeft * newWidth});
                            }

                        });
                    }
                    else {
                        objTop = objectActive.getTop();
                        objLeft = objectActive.getLeft();
                        objWidth = objectActive.getWidth();
                        objHeight = objectActive.getHeight();
                        objectActive.setWidth(objWidth * newWidth);
                        objectActive.setHeight(objHeight * newWidth);
                        objectActive.set({top: objTop,
                            left: objLeft * newWidth});
                    }
                }

                if (w > canvas.getWidth()) {
                    canvas.setHeight(w * 0.25 + canvas.getHeight());
                }
                else {
                    canvas.setHeight(canvas.getHeight() - w * 0.25);
                }
                canvas.setWidth(w);
                canvas.calcOffset();
                canvas.renderAll();
            }
        }
        else {
            for (var i = 0; i < canvases.length; i++) {
                if (canvases[i] != null) {
                    canvas = canvases[i];
                    if (w > canvas.getWidth()) {
                        canvas.setHeight(w * 0.25 + canvas.getHeight());
                    }
                    else {
                        canvas.setHeight(canvas.getHeight() - w * 0.25);
                    }
                    canvas.setWidth(w);
                    canvas.calcOffset();
                    canvas.renderAll();
                }
            }
        }

    }

}

function changeHeightCanvas() {
    var h = $('#canheight').val();
    if (isNaN(h) || h > 2000) {
        alert("Size is wrong");
    }
    else {
        var newHeight = $('#canheight').val() / $('canvas').height();
        // canvas.setHeight($("#canheight").val());
        if ($("#checkResize").prop('checked', true)) {

            selectAll(); //select all object

            var objectActive = canvas.getActiveObject(); //object
            var objectAciveGroup = canvas.getActiveGroup(); //objects
            if (objectAciveGroup) {
                var objectsInGroup = objectAciveGroup.getObjects();
                canvas.discardActiveGroup();
                objectsInGroup.forEach(function (object) {
                    if ((object.get('type') == 'i-text')) {
                        fonsize = object.get('fontSize');
                        setActiveStyle('fontSize', fonsize * newWidth, object);
                    }
                    else {
                        objTop = object.getTop();
                        objLeft = object.getLeft();
                        objWidth = object.getWidth();
                        objHeight = object.getHeight();
                        object.setWidth(objWidth * newHeight);
                        object.setHeight(objHeight * 0.5 * newHeight);
                        object.set({top: objTop * newHeight,
                            left: objLeft});
                    }

                });
            }
            else {
                objTop = objectActive.getTop();
                objLeft = objectActive.getLeft();
                objWidth = objectActive.getWidth();
                objHeight = objectActive.getHeight();
                objectActive.setWidth(objWidth * 0.5 * newHeight);
                objectActive.setHeight(objHeight * newHeight);
                objectActive.set({top: objTop * newHeight,
                    left: objLeft});
            }
        }
        if (h > canvas.getHeight()) {
            canvas.setWidth(h * 0.25 + canvas.getWidth());
        }
        else {
            canvas.setWidth(canvas.getHeight() - h * 0.25);
        }
        canvas.setHeight(h);
        canvas.calcOffset();
        canvas.renderAll();
    }

}

function getLockX() {
    return getActiveProp('lockMovementX');
}

function getLockY() {
    return getActiveProp('lockMovementY');
}

function setLockX(valuex, valuey) {
    setActiveProp('lockMovementX', valuex);
    setActiveProp('lockMovementY', valuey);
    setActiveProp('lockScalingX', valuey);
    setActiveProp('lockScalingY', valuey);
    setActiveProp('lockRotation', valuey);
}
$(document).ready(function () {

    canvas.on('mouse:down', function (options) {
        var objectActive = canvas.getActiveObject();
        if (objectActive) {
            if (typeof (objectActive.link) != 'undefined') {
                if (objectActive.link != '') {
                    $('.link-icon').addClass('link-active');
                    return;
                }
            }
        }

        $('.link-active').removeClass('link-active');
    });
    $('.link-icon').click(function () {
        var objectActive = canvas.getActiveObject();
        var activeGroup = canvas.getActiveGroup();
        if (activeGroup) {
            if (confirm('More than one object will be set with the hyperlink, Are you sure?')) {
                link = prompt('Set hyperlink to object:', 'http://');
                if (link == 'http://')
                    return;
                var objectInGroup = activeGroup.getObjects();
                objectInGroup.forEach(function (obj) {
                    obj.set('link', link);
                });
                $(this).addClass('link-active');
            }
        } else if (objectActive) {
            link = prompt('Set hyperlink to object:', objectActive.link || 'http://');
            if (link == 'http://')
                return;
            objectActive.set('link', link);
            $(this).addClass('link-active');
        } else {
            alert('You must chose 1 object');
        }

    });
    $('.down-icon').click(function () {
        if (number === canvases.length - 1) {
            alert("Can't move down canvas");
            return;
        }
        if (number !== false) {
            var canvasTem = JSON.stringify(canvas);
            var numberTem = number + 1;
            while (numberTem <= canvases.length) {
                if (canvases[numberTem] == null) {
                    numberTem++;
                } else {
                    break;
                }
            }

            if (numberTem >= canvases.length) {
                alert("You can't move down canvas");
                return;
            }

            canvas.loadFromJSON(JSON.stringify(canvases[numberTem]));
            canvases[numberTem].loadFromJSON(canvasTem);
        } else {
            alert('You must chose 1 block');
        }
    });
    $('.up-icon').click(function () {
        if (number === 0) {
            alert("Can't move up canvas");
            return;
        }
        if (number !== false) {
            var canvasTem = JSON.stringify(canvas);
            var numberTem = number - 1;
            while (numberTem >= -1) {
                if (canvases[numberTem] == null) {
                    numberTem--;
                } else {
                    break;
                }
            }

            if (numberTem == -1) {
                alert("You can't move up canvas");
                return;
            }
            canvas.loadFromJSON(JSON.stringify(canvases[numberTem]));
            canvases[numberTem].loadFromJSON(canvasTem);
        } else {
            alert('You must chose 1 block');
        }
    });
    var canvasId = 0;
    $(".add-icon").click(function (e) {
        e.preventDefault();
        canvasId++;
        var newCanvas = $('<canvas id="canvas-' + canvasId + '" width=800 height=400></canvas>');
        $('.container_canvas').append(newCanvas);
        var newCanvas = new fabric.Canvas('canvas-' + canvasId);
        newCanvas.backgroundColor = '#fff';
        canvases.push(newCanvas);
        countCanvas++;
    });
    $('canvas').hover(
            function () {
                // console.log(1);
                $(this).addClass('active');
            },
            function () {
                $('.active').removeClass('active');
            }

    );
    $('body').delegate('.upper-canvas', 'click', function () {
        var myCanvas = $(this).parent().find(' canvas:first').attr('id');
        var intID = myCanvas.replace("canvas-", "0");
        number = parseInt(intID);
        if (isNaN(number)) {
            number = 0;
        }

        canvas = canvases[number];
        canvas.calcOffset();
        canvas.renderAll();
        $('.unactive').removeClass('unactive');
    });
    $('body').delegate('.upper-canvas', 'mouseover', function () {
        var myCanvasId = $(this).parent().find('canvas:first').attr('id');
        var strNumber = myCanvasId.replace('canvas-', '0');
        var idNumber = parseInt(strNumber);
        var _this;
        if (isNaN(idNumber)) {
            _this = $('#canvas');
            idNumber = 0;
        } else {
            _this = $('#canvas-' + idNumber);
        }

        if (idNumber == number)
            return;
        _this = _this.parent().find('.upper-canvas');
        _this.addClass('unactive');
        _this.addClass('active');
    });
    $('body').delegate('.upper-canvas', 'mouseout', function () {
        $('.unactive').removeClass('unactive');
        $('.active').removeClass('active');
    });
    $('.delete-icon').click(function () {
        if (countCanvas === 1) {
            alert("Can't remove last canvas !");
            return;
        }
        var elementDelete;
        if (number !== false) {
            if (number == 0) {
                elementDelete = $('#canvas').parent();
            } else {
                elementDelete = $('#canvas-' + number).parent();
            }
            elementDelete.remove();
            canvases[number] = null;
            countCanvas--;
            number = false;
        } else {
            alert('You must select a block');
        }
    });
    $(".clone-icon").click(function (e) {
        e.preventDefault();
        canvasId++;
        var newCanvas = $('<canvas id="canvas-' + canvasId + '" width=800 height=400></canvas>');
        $('.container_canvas').append(newCanvas);
        var cloneCanvas = new fabric.Canvas('canvas-' + canvasId);
        selectAll();
        var backGround = canvas.backgroundColor;
        cloneCanvas.backgroundColor = backGround;
        var objectActive = canvas.getActiveObject();
        var objectAciveGroup = canvas.getActiveGroup();
        if (objectAciveGroup) {
            canvas.discardActiveGroup();
            for (var i in objectAciveGroup.objects) {
                var object = fabric.util.object.clone(objectAciveGroup.objects[i]);
                object.set("top", objectAciveGroup.objects[i].top);
                object.set("left", objectAciveGroup.objects[i].left);
                cloneCanvas.add(object);
            }
        }
        else if (objectActive) {
            var object = fabric.util.object.clone(objectActive);
            object.set("top", objectActive.top);
            object.set("left", objectActive.left);
            cloneCanvas.add(object);
        }
        canvases.push(cloneCanvas);
        countCanvas++;
    });
});
$('#canvas').ready(function (e) {
    var ctrl = false;
    $(document).keydown(function (e) {
        if (e.code == 127) {
            return;
        }

        if (e.which == 46) {
            removeSelected();
        }

        if (e.which == 17)
            ctrl = true;
        if (e.which == 65 || e.which == 97) {
            if (ctrl) {
                selectAll();
            }
        }

        if (e.which == 88 || e.which == 120) { // ctr + x
            if (ctrl) {
                cut();
            }
        }

        if (e.which == 67 || e.which == 99) {   //ctr + c
            if (ctrl) {
                copy();
            }
        }

        if (e.which == 86 || e.which == 118) {   //ctr + v
            if (ctrl) {
                paste();
            }
        }

        if (e.which == 90 || e.which == 122) {   //ctr + z
            if (ctrl) {
                undo();
            }
        }
    });
});
function get_canvas() {
    if (!fabric.Canvas.supports('toDataURL')) {
        alert('This browser doesn\'t provide means to serialize canvas to an image');
        return;
    }
    var canvasHidden;
    var canvasIMG;
    var wIMG = 0;
    var hIMG = 0;
    var s = 0;
    var h = 0;
    for (var i = 0; i < canvases.length; i++) {
        if (canvases[i] != null) {
            if (wIMG == 0) {
                wIMG = canvases[i].getWidth();
            }
            ;
            hIMG = hIMG + canvases[i].getHeight();
        }
        ;
    }
    ;
    canvasHidden = $('<canvas id="canvasfinal" width=' + wIMG + ' height=' + hIMG + ' style="display:none;"></canvas>');
    $('.canvas-to-img').append(canvasHidden);
    canvasIMG = new fabric.Canvas('canvasfinal');
    for (var i = 0; i < canvases.length; i++) {
        if (canvases[i] != null) {
            h = canvases[i].getHeight();
            fabric.Image.fromURL(canvases[i].toDataURL("png"), function (image) {
                image.left = 0;
                image.top = s;
                canvasIMG.add(image);
                image = null;
                canvasIMG.renderAll();
            });
            s = s + h;
        }
    }

    return canvasIMG;
}
function preview_canvas() {
    if (canvases.length == 1) {
        _preview_canvas();
    }
    else {
        canvas = get_canvas();
        canvas.calcOffset();
        canvas.renderAll();
        _preview_canvas();
        var elementDelete;
        elementDelete = $('#canvasfinal').parent();
        elementDelete.remove();
    }


}

function download_canvas() {
    if (canvases.length == 1) {
        _download_canvas();
    }
    else {
        canvas = get_canvas();
        canvas.calcOffset();
        canvas.renderAll();
        _download_canvas();
        var elementDelete;
        elementDelete = $('#canvasfinal').parent();
        elementDelete.remove();
    }
}

function align_left() {
    var width = canvas.getWidth();
    var height = canvas.getHeight();
    var objectActive = canvas.getActiveObject();
    var objectActiveGroup = canvas.getActiveGroup();
    if (objectActiveGroup) {
        var objectGroup = objectActiveGroup;
        objectGroup.set({
            top: height - objectActiveGroup.getHeight(),
            left: objectActiveGroup.getWidth()
        });
    } else if (objectActive) {
        var object = objectActive;
        object.set({
            top: height - objectActive.getHeight(),
            left: 0
        });
        canvas.add(object);
        canvas.remove(objectActive);
    }
    canvas.renderAll();
}
function addChart(imageName, scale) {
    var random = getRandomLeftTop();
    fabric.util.loadImage(imageName, function (img) {
        var object = new fabric.Image(img);
        object.set({
            left: random['left'],
            top: random['top'],
            width: 420
        });
        canvas.add(object);
        canvas.renderAll();
    }, null, {crossOrigin: 'Anonymous'});
    canvas.renderAll();
}
;
$(document).ready(function () {
    var data = [
        ['', 'Apple', 'Banna', 'Sup'],
        ['Axis 1', 20, 40, 80]
    ];
    var array = [];
    var $container = $('#sheet').handsontable({
        data: data,
        minSpareRows: 15,
        minSpareCols: 8,
        colHeaders: true,
        rowHeaders: true,
        contextMenu: true,
        afterChange: function (change) {
            changeData(data);
        }
    });
    function changeData(data) {
        $("#menu-chart li").click(function () {
            $(".chart-active").removeClass("chart-active");
            $(this).addClass("chart-active");
            var strClass = $(this).attr("class");
            var nameclass = strClass.substr(0, strClass.lastIndexOf(" "));
            var type = nameclass.substr(nameclass.indexOf("-") + 1, nameclass.length);
            $('#chart .title').text(type.toUpperCase());
            updateChart(type, data);
        });
        $("#menu-chart li.chart-active").trigger("click");
    }
    var options;
    function updateChart($chart, $data) {
        $("#chart-sheet").empty();

        if ($chart === 'column') {
            options = {
                chart: {
                    renderTo: 'chart-sheet',
                    type: $chart
                },
                title: {
                    text: 'Preview'
                },
                xAxis: {
                    categories: [],
                    title: {
                        text: null
                    }
                },
                credits: {
                    enabled: false
                },
                series: []
            };
        }
        else if ($chart === 'bar') {
            options = {
                chart: {
                    renderTo: 'chart-sheet',
                    type: $chart
                },
                title: {
                    text: 'Preview'
                },
                xAxis: {
                    categories: [],
                    title: {
                        text: null
                    }
                },
                plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: true
                        }
                    }
                },
                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'top',
                    x: -40,
                    y: 100,
                    floating: true,
                    borderWidth: 1,
                    backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                    shadow: true
                },
                credits: {
                    enabled: false
                },
                series: []
            };
        }
        else if ($chart === 'pie') {
            options = {
                chart: {
                    renderTo: 'chart-sheet',
                    type: $chart
                },
                title: {
                    text: 'Preview',
                    title: {
                        text: null
                    }
                },
                xAxis: {
                    categories: [],
                    title: {
                        text: null
                    }
                },
                credits: {
                    enabled: false
                },
                series: []
            };

        }
        else if ($chart === 'donut') {
            options = {
                chart: {
                    renderTo: 'chart-sheet',
                    type: 'pie',
                    options3d: {
                        enabled: true,
                        alpha: 45
                    }
                },
                plotOptions: {
                    pie: {
                        innerSize: 100,
                        depth: 45
                    }
                },
                title: {
                    text: 'Preview',
                    title: {
                        text: null
                    }
                },
                xAxis: {
                    categories: [],
                    title: {
                        text: null
                    }
                },
                credits: {
                    enabled: false
                },
                series: []
            };

        } else if ($chart === 'pyramid') {

            options = {
                chart: {
                    renderTo: 'chart-sheet',
                    type: 'pyramid',
                    marginRight: 100
                },
                title: {
                    text: 'Sales pyramid',
                    x: -50
                },
                xAxis: {
                    categories: [],
                    title: {
                        text: null
                    }
                },
                plotOptions: {
                    series: {
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b> ({point.y:,.0f})',
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
                            softConnector: true
                        }
                    }
                },
                legend: {
                    enabled: false
                },
                series: []
            };
        } else {
            options = {
                chart: {
                    renderTo: 'chart-sheet',
                    type: $chart
                },
                title: {
                    text: 'Preview',
                    title: {
                        text: null
                    }
                },
                xAxis: {
                    categories: [],
                    title: {
                        text: null
                    }
                },
                credits: {
                    enabled: false
                },
                series: []
            };
        }
        var category = [];
        for (var i = 0; i < $data.length; i++) {
            for (var j = 0; j < $data[i].length; j++)
                if (i === 0 && j !== 0)
                    if ($data[i][j] !== null)
                        category.push($data[i][j]);
        }

        var len = 0;
        for (var i = 1; i < $data.length; i++) {
            var count = 0;
            for (var j = 0; j < $data[i].length; j++) {
                if ($data[i][j] === null || $data[i][j] === "")
                    count++;
            }
            len++;
            if (count === $data[i].length)
                break;
        }

        for (var i = 1; i < len; i++) {
            var nameItem = $data[i][0];
            var dataItem = [];
            for (var j = 1; j < category.length + 1; j++) {
                if ($data[i][j] === null || $data[i][j] === "") {
                    dataItem.push(parseInt(0));
                } else
                    dataItem.push(parseInt($data[i][j]));
            }

            options.series.push({
                "name": nameItem,
                "data": dataItem
            });

        }
        for (var i = 0; i < category.length; i++) {
            options.xAxis.categories.push(category[i]);
        }

        var chart = new Highcharts.Chart(options);
    }

    $('#insertchart').click(function () {
        var exportUrl = 'http://export.highcharts.com/';
        var object = {
            options: JSON.stringify(options),
            type: 'image/png',
            async: true
        };
        $.ajax({
            type: 'post',
            url: exportUrl,
            data: object,
            success: function (data) {
                addChart(exportUrl + data, 1);
            }
        });
    });
    $("#menu-chart li:first").trigger("click");
    $('#menu-chart li').tooltip({
        placement: 'right'
    });
});


//----------------------------------MAP-------------------------------------

$(document).ready(function () {



    function findIndex(array, data) {
        var index = -1;
        $.each(array, function (i, val) {
            if (array[i].code == data) {
                index = i;
                return;
            }
        });
        return index;
    }

    var mapData;
    var optionsMap;
    var chartMap;
    var jsonStringMap;
    var updateData = null;
    var dataSheet = [];
    var row;

    function updateMap(mapdata, namemap, updateData) {
        dataSheet = [
            ["", "code", "Population", "", "", "", "", ""]
        ];
        if (namemap == 'USA Map' || namemap == 'AUSTRALIA Map')
            dataSheet = [
                ["", "", "", "", "", "", "", ""]
            ];
        $('#map-content').empty();
        $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=world-population.json&callback=?', function (data) {
            mapData = Highcharts.geojson(Highcharts.maps[mapdata]);

            if (updateData) {
                data = updateData;
            }
            $.each(mapData, function (i, val) {
                var index = findIndex(data, this.properties['iso-a2']);
                if (index != -1) {
                    var obj = data[index];
                    dataSheet.push([this.name, obj.code, obj.z]);
                }
            });
            updateData = data;


            dataSheet.sort();

            optionsMap = {
                chart: {
                    renderTo: 'map-content',
                    type: 'map'

                },
                title: {
                    text: namemap
                },
                legend: {
                    layout: 'horizontal',
                    borderWidth: 0,
                    backgroundColor: 'rgba(255,255,255,0.85)',
                    floating: true,
                    verticalAlign: 'top',
                    y: 25
                },
                mapNavigation: {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'bottom'

                    }
                },
                exporting: {
                    type: 'image/png'
                },
                colorAxis: {
                    min: 1,
                    max: 1300000,
                    type: 'logarithmic',
                    minColor: '#e7e7fd',
                    maxColor: '#020240',
                },
                series: [{
                        name: 'Countries',
                        // animation: {
                        //   duration: 1000
                        // },
                        data: data,
                        mapData: Highcharts.maps[mapdata],
                        joinBy: ['iso-a2', 'code'],
                        dataLabels: {
                            enabled: true,
                            color: 'white',
                            format: '{point.name}'
                        },
                        name: 'Population',
                                tooltip: {
                                    pointFormat: '{point.name}: {point.z} thousands',
                                }
                    }]
            };






            // Instanciate the map
            chartMap = Highcharts.Map(optionsMap);



            $('#sheet-map').handsontable({
                data: dataSheet,
                minSpareRows: 1,
                colHeaders: true,
                rowHeaders: true,
                contextMenu: true,
                cell: [{col: 0, className: 'htLeft'},
                    {col: 2, className: 'htRight'}],
                afterSelection: function (r, c) {
                    if (c == 2)
                        row = r;
                },
                afterChange: function () {
                    if (row > 1) {
                        for (var j = 1; j < updateData.length; j++) {

                            if (dataSheet[row][1] == updateData[j].code) {
                                updateData[j].z = parseInt(dataSheet[row][2] + '');

                                var mapActive = $('.map-active');
                                if (mapActive.length > 0) {
                                    mapActive.removeClass('map-active');
                                    var className = mapActive.attr('name-map');
                                    var title = mapActive.attr('id');
                                    updateMap(className, title.toUpperCase(), updateData);
                                    mapActive.addClass('map-active');

                                }
                                row = -1
                                return;
                            }

                        }
                    }
                    row = -1

                }

            });



        });
    }



    function addMapImage(svg, scale) {
        fabric.loadSVGFromString(svg, function (objects, options) {
            var obj = fabric.util.groupSVGElements(objects, options);
            canvas.add(obj).centerObject(obj).renderAll();
            obj.setCoordes();
        });
    }



    $('#menu-map li').click(function () {
        $('.map-active').removeClass('map-active');
        var className = $(this).attr('name-map');
        var titleMap = $(this).attr('id');
        if (titleMap == 'usa' || titleMap == 'australia') {
            updateMap(className, titleMap.toUpperCase() + ' Map', updateData);
        } else {
            updateMap(className, titleMap.toUpperCase() + ' Population', updateData);
        }
        $('#map .title').text(titleMap.toUpperCase());
        $(this).addClass('map-active');
    });



    $('#insert-map').click(function () {



        var strId = $('.map-active').attr('id');
        $('#' + strId).click();


        setTimeout(function () {
            var mapSVG = $('#map-content svg');
            mapSVG.find('.highcharts-title ').remove();
            mapSVG.find('.highcharts-tooltip').remove();
            mapSVG.find('.highcharts-legend').remove();
            mapSVG.find('.highcharts-button').remove();
            mapSVG.find('g[zIndex=1]').remove();




            var str = mapSVG.prop('outerHTML'); // conver html to string
            addMapImage(str);
            $('#menu-map li:first').trigger('click');

        }, 2000)
    });

    $('#menu-map li:first').trigger('click');


    $('#menu-map li').tooltip({
        placement: 'right'
    });



});


//-----------------------------END: MAP-----------------------------------------
